import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import store from '../store/index'

function openSocket(options) {
  console.log('开始链接')
  if (typeof WebSocket === 'undefined') {
    console.log('您的浏览器不支持websocket!')
    return false
  } else {
    var timeWs = null // 心跳
    var timeReconnect = null // 重连
    // var host = "192.168.3.118:8208";
    // var host = "192.168.4.72:8208";
    var host = 'localhost:8208'
    var socketUrl = 'http://' + host + '/web-terminal'
    var ws = new SockJS(socketUrl)
    var stompClient = Stomp.over(ws)
    stompClient.connect(
      {},
      function() {
        timeWs = setInterval(() => {
          // 定时像后端发数据，一分钟touch一下session
          // console.log('pingpong')
          stompClient.send('pingpong')
        }, 60000)
        // 订阅查询
        stompClient.subscribe('/topic/c_scattering_run', function(msg) {
          console.log('C频段散射通信测试设备 运行状态', msg.body)
          store.commit('websocket/C_SCATTERING_RUN_DATA', JSON.parse(msg.body))
        })
        stompClient.subscribe('/topic/ku_scattering_run', function(msg) {
          console.log('Ku频段散射通信测试设备运行状态', msg.body)
          store.commit(
            'websocket/KU_SCATTERING_RUN_DATA',
            JSON.parse(msg.body)
          )
        })
        stompClient.subscribe('/topic/c_scattering_comm', function(msg) {
          console.log('KC频段散射通信测试设备 通信参数', msg.body)
          store.commit(
            'websocket/C_SCATTERING_COMM_DATA',
            JSON.parse(msg.body)
          )
        })
        stompClient.subscribe('/topic/ku_scattering_comm', function(msg) {
          console.log('Ku频段散射通信测试设备 通信参数', msg.body)
          store.commit(
            'websocket/KU_SCATTERING_COMM_DATA',
            JSON.parse(msg.body)
          )
        })
        stompClient.subscribe('/topic/uv_run', function(msg) {
          console.log('VHF/UHF频段电台测试设备 运行状态', msg.body)
          store.commit('websocket/UV_RUN_DATA', JSON.parse(msg.body))
        })
        stompClient.subscribe('/topic/uv_comm', function(msg) {
          console.log('VHF/UHF频段电台测试设备 通信参数', msg.body)
          store.commit('websocket/UV_COMM_DATA', JSON.parse(msg.body))
        })
        // 人机交互页面-地图相关websocket
        // 点状态
        stompClient.subscribe('/topic/pointData', (message) => {
          console.log('点状态websocket', JSON.parse(message.body))
          store.commit(
            'websocket/SET_TOPOLOGY_POINT_DATA',
            JSON.parse(message.body)
          )
        })
        // 拓扑线状态
        stompClient.subscribe('/topic/lineData', (message) => {
          console.log('拓扑线状态websocket', JSON.parse(message.body))
          store.commit(
            'websocket/SET_TOPOLOGY_LINE_DATA',
            JSON.parse(message.body)
          )
        })
        // 业务线状态
        stompClient.subscribe('/topic/businessLineData', (message) => {
          console.log('业务线状态websocket', JSON.parse(message.body))
          store.commit(
            'websocket/SET_BUSINESS_LINE_DATA',
            JSON.parse(message.body)
          )
        })
        // 态势表格数据
        stompClient.subscribe('/topic/send_status_table', function(msg) {
          console.log('态势表格websocket', msg.body)
          store.commit('websocket/SET_SEND_STATUS_DATA', JSON.parse(msg.body))
        })
      },
      function() {
        clearInterval(timeWs)
        clearTimeout(timeReconnect)
        timeReconnect = setTimeout(() => {
          openSocket()
        }, 5000)
      }
    )
    stompClient.onerror = function(err) {
      clearInterval(timeWs)
      console.log('连接错误，尝试重新连接', err)
      openSocket()
    }
  }
}

function WebSocketInit(ip, username) {
  if ('WebSocket' in window) {
    console.log('----开始连接！！！', `ws://${ip}:8208/webrtc/${username}`)
    const websocket = new WebSocket(`ws://${ip}:8208/webrtc/${username}`)
    store.commit('websocket/SET_WEBSOCKET', websocket)
  } else {
    alert('----当前浏览器不支持WebSocket！')
  }

  // 保留所有原始事件监听器
  store.getters.websocket.onerror = (e) => {
    alert('----WebSocket连接失败！！！')
  }

  store.getters.websocket.onclose = () => {
    console.error('----WebSocket连接关闭')
  }

  store.getters.websocket.onopen = () => {
    console.log('----WebSocket连接成功')
  }

  // 完整保留消息处理逻辑
  store.getters.websocket.onmessage = async(event) => {
    const rawData = event.data.replace(/\n/g, '\\n').replace(/\r/g, '\\r')
    const { type, fromUser, toUser, msg, sdp, iceCandidate, callType } =
      JSON.parse(rawData)
    store.commit('websocket/SET_WEBSOCKET_CONNECT', JSON.parse(rawData))
    console.log('----websocket收到的内容', JSON.parse(rawData))
  }
}

export { openSocket, WebSocketInit }
